function BCAinstallControls () {
    // Check missiles
    if (localStorage.getItem ("po_bca_check_all_missiles") == "true") {
	var allmissilesbox = document.getElementById('allmissiles');
	if (allmissilesbox) allmissilesbox.click ();//allmissilesbox.checked = true;
    }
    
    // Check the Raid option
    if (localStorage.getItem ("po_bca_check_raid") == "true") {
	var letsurrender = document.getElementById('letsurrender');
	if (letsurrender) letsurrender.click ();//allmissilesbox.checked = true;
    }
    // Reverse the attack rounds options so that 20 is on the top (pre-selected)
    var option;
    var select;
    var rtext;
    var rtext2;
    select = document.getElementsByTagName('select');
    if (select[0].hasAttribute('style')) { option = select[1].getElementsByTagName('option') }
    else { option = select[0].getElementsByTagName('option'); }

    for(var i = 0; i < option.length; i++) {
	option[i].setAttribute("value", option.length-i);
    }
    for(var i = 0; i < (option.length/2); i++) {
	rtext = option[i].textContent;
	rtext2 = option[option.length-1-i].textContent;
	option[option.length-1-i].innerHTML = rtext;
	option[i].innerHTML = rtext2;
    }
    
    BCAinstallBotsDrugs ();
}

function BCAgetCargoAmount (commodity, subtract) {
    // Commodity can be either Robots or Drugs
    // Find the table with cargo
    // If the Subtract value is set, the method actually sets a new value to the element which equals to CurrentValue - Subtract
    var tds = document.getElementsByTagName ("th");
    var tb = null;
    for (var i=0; i<tds.length; i++) {
        if (tds[i].textContent == "Resource") {
            tb = tds[i].parentNode.parentNode;
            break;
        }
    }
    // If the table does not exist at all, no bots or drugs are on board
    if (!tb) return 0;
    
    // Go through the rows and search for robots. Skip first row = header
    for (var i=1; i<tb.rows.length; i++){
        var tr = tb.rows[i];
        if (tr.cells[0].firstChild.getAttribute("alt") == commodity) {
            var current = Number (tr.cells[1].textContent);
            if (subtract) {
                current -= subtract;
                tr.cells[1].textContent = current;
            }
            return current;
        }
    }
    
    // No row with robots in the cargo table
    return 0;
}

function BCAgetMyArmor () {
    var fnt = null;
    var fnts = document.getElementsByTagName ("font");
    for (var i=0; i<fnts.length; i++) {
        if (fnts[i].textContent.indexOf ("Armor points:") == 0) {
            fnt = fnts[i];
            break;
        }
    }
    
    if (fnt) {
	return Number (fnt.textContent.split (": ")[1].split(" ")[0]);
    }
    
    return 0;
}

function POgetBotsToRepair (armorStrength, armor, maxArmor) {
    var step = 180/armorStrength;
    if (armor < (maxArmor - 5)) {
        return Math.ceil((maxArmor - armor) / step);
    }
    return 0;
}

function BCAgetBotsToTake (currentArmor) {
    var armorS = localStorage.getItem ("po_bca_armor_strength");
    var armorP = localStorage.getItem ("po_bca_armor_points");
    if (!armorS || !armorP) return 0;
    armorS = Number (armorS);
    armorP = Number (armorP);
    return POgetBotsToRepair (armorS, currentArmor, armorP);
}

function BCAinstallBotsDrugs () {
    var fnt = null;
    var fnts = document.getElementsByTagName ("font");
    for (var i=0; i<fnts.length; i++) {
        if (fnts[i].textContent.indexOf ("Armor points:") == 0) {
            fnt = fnts[i];
            break;
        }
    }

    if (fnt) {
        var current = Number (fnt.textContent.split (": ")[1].split(" ")[0]);
        var bots = BCAgetBotsToTake (current);
	var avail = BCAgetCargoAmount ("Robots");
	
	if (avail == 0) {
	    fnt.innerHTML += "&nbsp;<span style='color:red;font-weight:bold'>Out of bots!!!</span>";
	} else {
	    if (avail < 10) {
		fnt.innerHTML += "&nbsp;<span style='color:yellow;font-weight:bold'>Low on bots!!!</span>";
	    }
	    if (avail < bots) bots = avail;
	    fnt.innerHTML += "&nbsp;<a id='bca_repair_armor_combat' amount='"+bots+"' href=\"javascript:BCAtakeBots;void(0)\">Press 4 to take "+bots+" robots</a>";
	}
	
        var tbl = fnt.parentNode.parentNode.parentNode;
        var tr = document.createElement ("tr");
        var toTake = Number (localStorage.getItem("po_bca_default_drugs"));
	var avail = BCAgetCargoAmount ("Drugs");
	if (toTake > avail) toTake = avail;
        tbl.appendChild (tr);
        tr.innerHTML = "<td><a id='bca_take_drugs' amount='"+toTake+"' href=\"javascript:BCAtakeDrugs;void(0)\">Press 5 to take "+toTake+" drugs</a></td>";
    }    
}

// //////////////////////////////////////////////////////////
// Hotkeys
// //////////////////////////////////////////////////////////
window.addEventListener("keypress",BCAkeyboardAction,true);

function BCAkeyboardAction (e) {
    if(window.name == '' || e.ctrlKey) return;
    if (e.target.nodeName.toUpperCase() == 'INPUT') return;
    var keynum = e.which;
    var key = String.fromCharCode(keynum).toLowerCase();
    
    if (key == "3") BCAfightTwenty ();
    else if (key == "1") BCAretreat ();
    else if (key == "2") BCArefreshScreen ();
    else if (key == "4") BCAtakeBots (-1);
    else if (key == "5") BCAtakeDrugs (-1);
    else if (key == "a") BCAwinFight ();
    else if (key == "d") BCAwinRetreat ();
}

function BCAwinFight () {
    var bots = 0;
    try {
	bots = Number(document.getElementById ("bca_repair_armor_combat").getAttribute ("amount"));
    } catch (e) {}
    
    if (bots > 0) {
	// We've got damage and we've got bots to repair. Let's repair.
	BCAtakeBots ();
	return;
    } else {
	// Either there's no damage or we don't have bots to repair. We fight anyway.
	// In case there is damage but no bots to repair (forceFight = ALT is on), it has
	// already been confirmed on the Building level
	BCAfightTwenty ();
    }
}

function BCAwinRetreat () {
    POajaxPost ("building.php", "POST", "retreat=Retreat", BCAretreat);
}

function BCAfightTwenty () {
    var btn = BCAgetBtn ("button5");
    if (!btn) {
        btn = BCAgetBtn ("ok");
    }
    btn.click ();
    //alert ("Attack!");
}

function BCAretreat () {
    window.location = "main.php";
}

function BCArefreshScreen () {
    window.location = document.URL;
}

function BCAtakeBots () {
    var amount = Number(document.getElementById ("bca_repair_armor_combat").getAttribute ("amount"));
    amount = 1;
    POuseResource (8, amount, BCArefreshScreen, window.location, "post");
}

function BCAtakeDrugs () {
    var amount = Number(document.getElementById ("bca_take_drugs").getAttribute ("amount"));
    POuseResource (51, amount, BCArefreshScreen, window.location, "post");
}


// //////////////////////////////////////////////////////////
// End: Hotkeys
// //////////////////////////////////////////////////////////

function BCAgetBtn (name) {
    var bts = document.getElementsByTagName ("input");
    for (i=0; i<bts.length; i++) {
        if (bts[i].getAttribute("name") == name) return bts[i];
    }
    return null;
}

BCAinstallControls ();